﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NetSurveillance.WebApp.Binders;
using NetSurveillance.WebApp.DataServices;
using NetSurveillance.WebApp.DataServices.Models;
using NetSurveillance.WebApp.Models;
using NetSurveillance.WebApp.Utilities;

namespace NetSurveillance.WebApp.Controllers
{
    public class VirusEmbedsController : BaseController
    {
        public ActionResult Index()
        {
            var veRules = DataProvider.VirusEmbedsService.GetAllModels();
            LoadIndexTempData();
            return View(veRules);
        }

        private void LoadIndexTempData()
        {
            var hosts = DataProvider.HostService.GetAllModels(false, p => p.TaskId == CurrentTask.Id);
            var selectHostIds = DataProvider.HostService.GetVirusEmbedHostIds(CurrentTask.Id);
            ViewBag.TreeNode = SerializeObject(ZTreeUtility.GenerateHostNodes(hosts, selectHostIds.ToList()));
            var selectRuleIds = DataProvider.VirusEmbedsService.GetTaskVirusEmbedRuleIds(CurrentTask.Id);
            ViewBag.TaskVirusRuleIds = selectRuleIds;
            var taskSetting = DataProvider.TaskSettingService.GetTaskSetting(CurrentTask.Id);
            ViewBag.AttackCount = taskSetting == null ? 5 : taskSetting.VirusEmbedAttackCount;
            if (taskSetting == null) return;
            ViewBag.IsAutoMonitorHost = taskSetting.IsAutoMonitorHostForVirusEmbed;
            ViewBag.IsAutoWarning = taskSetting.IsAutoAlertVirtusEmbed;
        }

        [HttpPost]
        public ActionResult Index(long[] selectRuleIds, [JsonBinder]long[] hostIds,
                                  bool? isAutoMonitorHost, bool? isAutoWarning, int? attackCount)
        {
            bool sendActionSucc = true;
            var hosts = DataProvider.HostService.GetModels(hostIds ?? new long[0]);
            var selectRules =
                DataProvider.VirusEmbedsService.GetModels(selectRuleIds);
            var veInfoEle =
                ActionXmlUtility.Instance.CreateVirusEmbedInfoElement(isAutoMonitorHost, isAutoWarning,
                                                                      attackCount, hosts, selectRules);
            var actionEle =
                ActionXmlUtility.Instance.GeneratorActionXml(ActionXmlUtility.Instance.CreateActionRootElement(),
                                                             veInfoEle);
            if (!Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
            {
                ModelState.AddModelError("", Resources.MessageResource.SendActionError);
                sendActionSucc = false;
            }
            ServiceResult serviceResult = null;
            if (sendActionSucc && (isAutoMonitorHost.HasValue || isAutoWarning.HasValue ||
                attackCount.HasValue))
            {
                var taskSetting =
                    DataProvider.TaskSettingService.GetTaskSetting(CurrentTask.Id) ??
                    new TaskSetting {TaskId = CurrentTask.Id};
                taskSetting.IsAutoAlertVirtusEmbed = isAutoWarning;
                taskSetting.IsAutoMonitorHostForVirusEmbed = isAutoMonitorHost;
                taskSetting.VirusEmbedAttackCount = attackCount;
                serviceResult = DataProvider.TaskSettingService.Save(taskSetting);
            }
            if (serviceResult != null && serviceResult.ExecutedSuccess)
            {
                serviceResult = DataProvider.HostService.SaveVirusEmbedHost(CurrentTask.Id,
                                                                            hostIds ?? new long[0]);
            }
            if (serviceResult != null && serviceResult.ExecutedSuccess)
            {
                serviceResult =
                    DataProvider.VirusEmbedsService.SaveTaskVirusEmbedRule(CurrentTask.Id,
                                                                           selectRuleIds ?? new long[0]);
                ;
            }
            var veRules = DataProvider.VirusEmbedsService.GetAllModels();
            LoadIndexTempData();
            if (serviceResult != null && serviceResult.ExecutedSuccess)
            {
                ModelState.AddModelError("", Resources.MessageResource.Save_Success);
                return View(veRules);
            }
            ModelState.AddModelError("", Resources.MessageResource.Save_Error);
            return View(veRules);
        }

        public ActionResult VirusEmbedRule(long veRuleId = -1)
        {
            var veRule = DataProvider.VirusEmbedsService.GetModelById(veRuleId);
            return View(veRule ?? new VirusEmbedRule());
        }

        [HttpPost]
        public ActionResult VirusEmbedRule(VirusEmbedRule veRule)
        {
            if (ModelState.IsValid)
            {
                veRule.CreateUserId = CurrentUser.Id;
                var serviceResult = DataProvider.VirusEmbedsService.Save(veRule);
                if (serviceResult.ExecutedSuccess)
                    return RedirectToAction("Index");
            }
            ModelState.AddModelError("", Resources.MessageResource.Save_Error);
            return View(veRule);
        }

        [HttpPost]
        public ActionResult Delete(long veRuleId)
        {
            var veRule = DataProvider.VirusEmbedsService.GetModelById(veRuleId);
            if (veRule != null)
            {
                veRule.StatusToken = 0;
                veRule.LastModifiedTime = DateTime.Now;
                var serviceResult = DataProvider.VirusEmbedsService.Save(veRule);
                return CamelCaseJson(new AjaxResult(serviceResult.ExecutedSuccess, serviceResult.Message));
            }
            return CamelCaseJson(new AjaxResult(false, Resources.MessageResource.Delete_Error));
        }
    }
}
